<?php
/**
 * Link Model
 *
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD.
 * @license http://doit.yuandot.com/license/
 */

class Link extends CActiveRecord {
    /**
     * The followings are the available columns in table 'www_links':
     * @var integer $id
     * @var integer $type
     * @var string $name
     * @var string $url
     * @var integer $status
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{links}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('type, name, url, status, node_id, order_pos', 'required'),
            array('type, status, created, updated, node_id, order_pos', 'numerical', 'integerOnly' => true),
            array('url', 'url'),
            array('name, summary, url, target', 'length', 'max' => 200),
            array('logo_filename', 'file', 'on' => 'is_picture_link',
                'allowEmpty' => false,
                'types' => 'jpg, gif',
                'maxSize' => 1024 * 1024 * 10,
            )
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        return array(
            // 所属节点
            'node' => array(self::BELONGS_TO, 'Node', 'node_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'node_id' => Yii::t('common', 'node_id'),
            'type' => Yii::t('link', 'type'),
            'name' => Yii::t('link', 'name'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'summary' => Yii::t('link', 'summary'),
            'url' => Yii::t('link', 'url'),
            'target' => Yii::t('link', 'target'),
            'logo_filename' => Yii::t('link', 'logo_filename'),
            'status' => Yii::t('options', 'status'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    const TYPE_TEXT = 1;
    const TYPE_PICTURE = 2;
    public function getTypeOptions() {
        return array(
            self::TYPE_TEXT   => Yii::t('link', 'type_text'),
            self::TYPE_PICTURE => Yii::t('link', 'type_picture'),
        );
    }

    public function getTypeIcon() {
        switch ($this->type) {
            case 1: $img = 'text.png'; break;
            case 2: $img = 'pictures.png'; break;
            default: $img = 'text.png';
        }
        $base_url = Yii::app()->request->baseUrl . '/assets/backend/images/';
        return "<img src=\"{$base_url}{$img}\" />";
    }

    const TARGET_BLANK = '_blank';
    const TARGET_SELF = '_self';
    public function getTargetOptions() {
        return array(
            self::TARGET_BLANK   => Yii::t('link', 'target_blank'),
            self::TARGET_SELF => Yii::t('link', 'target_self'),
        );
    }
    
    // "status" field Icon format
    public function getStatusIconFormat() {
        switch ($this->status) {
            case Options::STATUS_DRAFT:
                $img = 'status_draft.gif';
                break;
            case Options::STATUS_PUBLISHED:
                $img = 'status_published.gif';
                break;
            case Options::STATUS_PENDING_DELETE:
                $img = 'status_pending_delete.gif';
                break;
            default:
                $img = 'status_unknown.gif';
        }
        return CHtml::image(Yii::app()->assetManager->baseUrl . '/backend/images/' . $img);
    }

    // status AJax submit
    public function getStatusAjaxFormat() {
        return CHtml::ajaxLink($this->statusIconFormat,
            Yii::app()->createUrl('backend/links/changeStatus'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#yuandot{$this->id}",
            ),
            array('id' => "yuandot{$this->id}")
        );
    }


    // 格式化更新时间
    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    /**
     * get logo picture saved path
     * @return string
     */
    public function getLogoPath() {
        return Yii::app()->basePath . '/../upload/links/' . $this->logo_filename;
    }

    public function getLogoSource() {
        return Yii::app()->baseUrl . '/upload/links/' . $this->logo_filename;
    }

    private $_original_logo_filename;
    public function afterFind() {
        $this->_original_logo_filename = $this->logo_filename;
    }

    protected function beforeValidate() {
        if ($this->type == self::TYPE_PICTURE) {
            if ($this->isNewRecord) {
                $this->setScenario('is_picture_link');
            } else {
                if ($this->_original_logo_filename == '') {
                    $this->setScenario('is_picture_link');
                }
            }
        }
        return true;
    }
    
    protected function beforeSave() {
        parent::beforeSave();
        // 类型为“图片链接”的才做上传处理
        if ($this->type == self::TYPE_PICTURE) {
            $uploading_file = CUploadedFile::getInstance($this, 'logo_filename');
            if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
                if (!$this->isNewRecord) {
                    @unlink(Link::model()->findByPk($this->id)->logoPath);
                }
                $filename = md5($this->url . $this->name) . '.' . $uploading_file->getExtensionName();
                $this->logo_filename = $filename;
                $uploading_file->saveAs(Yii::app()->basePath . '/../upload/links/' . $filename);
            } else {
                $this->logo_filename = $this->_original_logo_filename;
            }
        } else {
            $this->logo_filename = '';
            @unlink(Link::model()->findByPk($this->id)->logoPath);
        }
        
        return true;
    }

    // 删除记录的同时删除 logo 文件
    public function afterDelete() {
        if ($this->type == self::TYPE_PICTURE) {
            @unlink($this->logoPath);
        }
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    /**
     *
     * @param integer $node
     * @param integer $type
     * @param integer $limit
     * @return array
     */
    protected function findBase($type, $node = null, $limit = 12) {
        $criteria = new CDbCriteria();
        $criteria->condition = 'status = ' . Options::STATUS_PUBLISHED;
        switch (strtolower(trim($type))) {
            case 'text':
                $type = self::TYPE_TEXT;
                break;
            case 'picture':
                $type = self::TYPE_PICTURE;
                break;
            default:
                $type = self::TYPE_TEXT;
        }
        $criteria->addCondition("type = {$type}");
        if ($node !== null) {
            if (is_array($node)) {
                $criteria->addInCondition('node_id', $node);
            } else if (is_int($node)) {
                $criteria->addCondition("node_id = {$node}");
            }
        }
        $criteria->limit = $limit;
        $criteria->order = 'order_pos ASC';

        return self::model()->findAll($criteria);
    }
    /**
     * Find "text Type links"
     * @param $node_id integer
     * @param $limit integer
     * @return array
     */
    public function findTextType($node = null, $limit = 12) {
        return $this->findBase('text', $node, $limit);
    }

    /**
     * Find "Picture Type Links"
     * @param integer $node
     * @param integer $limit
     * @return array
     */
    public function findPictureType($node = null, $limit = 12) {
        return $this->findBase('picture', $node, $limit);
    }
}